/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * @author quyennb
 */
public class HandleDataTableCampaignDateV2 {

    public static final String KEYSPACE                         =   "AdsDataV2";
    public static final String ColumFamly                       =   "BannerViewCountCf";
    public static final String ColumFamlyBannerClickCountCf     =   "BannerClickCountCf";
    public static final String ColumFamlyBannerViewCountCf      =   "BannerViewCountCf";

    public static final String ColumFamlyCampaignClickCountCf       =   "CampaignCountCf";
    public static final String ColumFamlyCampaignViewCountCf        =   "CampaignViewCountCf";

    public void handleData() throws ParseException, InterruptedException, ClassNotFoundException, InstantiationException, IllegalAccessException
    {

        long first_time = System.currentTimeMillis();
        CassandraAction cassAct = new CassandraAction(ACCOUNT.CLUSTERNAME ,ACCOUNT.URL, ACCOUNT.PORT);
        cassAct.initReadWirte(KEYSPACE);
        MysqlDataManager mysql = new MysqlDataManager();  
        MysqlDataManagerMain mysqlMain = new MysqlDataManagerMain();
                        
        Map<Integer, String> uv_uc = new HashMap<>();  
        
        Map<String, String> listcamps = new HashMap<>();
        String currentDate = HandleDataTableDomainDate.handleDate();//2012-07-24        
        //String currentDate = "2013-08-12";  
        StringBuilder sbff = new StringBuilder();        
        
        uv_uc = mysqlMain.getUvUcByCampaignidMobile(currentDate);
        
        Map<String,String> listCamCPCMobile=new HashMap<>();
        listCamCPCMobile = mysql.getCamMobileByCPC(currentDate);
        
        Map<String,String> listCamCPMMobile=new HashMap<>();
        listCamCPMMobile = mysql.getCamMobileByCPM(currentDate);
        
        listcamps = mysql.getCamMobile(currentDate);        
        Iterator it=listcamps.entrySet().iterator();
        
        while(it.hasNext())
        {
            Map.Entry m =(Map.Entry)it.next();
            String valuekey = (String)m.getKey();
            String campid = valuekey.split("_")[0];
            String valCamp = (String)m.getValue();
            //if(campid.contains(sbff))
            String str = getClickInMonth(valCamp,cassAct, currentDate, campid, ColumFamlyCampaignClickCountCf, ColumFamlyCampaignViewCountCf,uv_uc,listCamCPMMobile,listCamCPCMobile);
            sbff.append(str);           
        }

         //xu li cho du lieu cuoi
        if(sbff.toString().length() > 1)
        {
            String relStr = sbff.toString();
            String valInsert = relStr.substring(0, (relStr.length()-1));
            
            HandleImportData hid = new HandleImportData();
            String pathFile="";
            try {
                pathFile = hid.outToCsvCampaign(valInsert);
                Debug.println("pathFile:"+pathFile);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

            try {                   
                mysql.removeDataCampaignByDate(currentDate);
                mysql.loadToV3CamDateFromFile(pathFile);                             
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        //close connection
        mysql.shutdownConnection();
        mysqlMain.shutdownConnection();
        //dw.shutdownConnection();
        long last_time = System.currentTimeMillis();
        System.out.println("Thoi gian chay  :" +(last_time-first_time));
        Debug.println("success HandleDataTableCampaignDate");

    }

     public static String getClickInMonth(String valCamp,CassandraAction cassAct,String currentDay ,String key,String columnFamilyClick,String columnFamilyView,Map uv_uc ,Map listCamCPMMobile,Map listCamCPCMobile) throws ParseException{
        StringBuilder sb = new StringBuilder();
        
        //denifie type mobile :cpc or cpm                
        long countClick          = Long.valueOf(valCamp.split("_")[0]);
        long countView           = Long.valueOf(valCamp.split("_")[1]);
        long countRealclick     = Long.valueOf(valCamp.split("_")[2]);
        long countchargeclick   = Long.valueOf(valCamp.split("_")[3]);
        //long money              = Long.valueOf(valCamp.split("_")[4]);
        //check neu campid < 9 chu so
        if(Long.valueOf(key) < 1000000000){
            if(uv_uc.containsKey(Integer.valueOf(key)))
            {
                                
                String uValue = (String) uv_uc.get(Integer.valueOf(key));
                String uc = uValue.split("_")[0];
                String uv = uValue.split("_")[1];
             
                DecimalFormat df = new DecimalFormat("##0.00");
                String ctr ="";
                if(countView == 0){
                    ctr =  "0";
                } else {
                    ctr = df.format(Float.valueOf(countClick)/Float.valueOf(countView)*100);
                }
                
                String str = "";
                String moneyc = "";
                String moneyv = "";
                
                if(listCamCPCMobile.containsKey(key))
                {
                    moneyc =(String) listCamCPCMobile.get(key);                
                } else {
                    moneyc ="0";
                }
                if(listCamCPMMobile.containsKey(key))
                {
                    moneyv =(String) listCamCPMMobile.get(key);
                } else {
                    moneyv ="0";
                }                
                
                str = "('" + key + "'," + countClick + "," + countView+ "," + countRealclick+ "," +  countchargeclick+ "," + countView +"," + Integer.valueOf(uv) + "," + Integer.valueOf(uc) + ",'" + currentDay + "'," + ctr +"," + moneyc+"," + moneyv +")";
                                       
                sb.append(str).append(",");                
                        
             } else
             {                
                DecimalFormat df = new DecimalFormat("##0.00");
                String ctr ="";
                if(countView == 0){
                    ctr =  "0";
                } else {
                    ctr = df.format(Float.valueOf(countClick)/Float.valueOf(countView)*100);
                }
                
                String str = "";
                String moneyc = "";
                String moneyv = "";
                
                if(listCamCPCMobile.containsKey(key))
                {
                    moneyc =(String) listCamCPCMobile.get(key);                
                } else {
                    moneyc ="0";
                }
                if(listCamCPMMobile.containsKey(key))
                {
                    moneyv =(String) listCamCPMMobile.get(key);
                } else {
                    moneyv ="0";
                } 
                
                str = "('" + key + "'," + countClick + "," + countView+ "," + countRealclick+ "," + countchargeclick+ "," + countView + ",0,0,'" + currentDay + "'," + ctr +"," + moneyc+"," + moneyv +")";
                               
                sb.append(str).append(",");                
             }
         }        
        return sb.toString();        
    }
     
    public static String getTypeMobile(Map typead,String key){        
        //denifie typead : cpm or cpc       
        String type = "";
        
        if(typead.containsKey(key)){
            String value = (String) typead.get(key);
            String[] arr = new String[2];
            arr = value.split("_");
            String typebanner  = arr[0];
            String typeads     = arr[1];
            if(("2".equals(typeads) && "1".equals(typebanner)) 
                    || ("5".equals(typeads) && "1".equals(typebanner)) 
                    || ("6".equals(typeads) && "1".equals(typebanner))){
                type ="cpc";
            } else {
                type ="cpm";
            }            
        }
        return type;
    } 
     
}
